package com.itheima.dubbo.utils;

import cn.hutool.core.collection.CollUtil;
import com.itheima.model.mongo.Friend;
import com.itheima.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TimeLineSave {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Async//异步线程，该方法会创建线程进行执行
    public void saveMovementTimeLine(ObjectId id,Long userId){
        //查询好友
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //动态时间线
        List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId",Long.class);
        for (Long friendId : friendIds) {
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            movementTimeLine.setMovementId(id);
            movementTimeLine.setUserId(userId);
            movementTimeLine.setFriendId(friendId);
            movementTimeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movementTimeLine);
        }
    }
}
